package api

import (
	"context"
	"fmt"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/client"
	"github.com/gin-gonic/gin"
)

func AddNode(ctx *gin.Context) {
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		panic(err)
	}
	var swarmInfo swarm.Swarm
	var dockerInfo types.Info
	swarmInfo, err = cli.SwarmInspect(context.TODO())
	if err != nil {
		fmt.Println("获取Swarm信息错误", err.Error())
	}
	dockerInfo, err = cli.Info(context.TODO())
	if err != nil {
		fmt.Println("获取docker信息错误", err.Error())
	}

	var ip string = "192.168.6.101"
	var port string = "22"
	test := TestConnection(ip, port, "as")
	if test != true {
		return
	}

	remoteAddr := make([]string, len(dockerInfo.Swarm.RemoteManagers))
	for i, peer := range dockerInfo.Swarm.RemoteManagers {
		remoteAddr[i] = peer.Addr
	}

	listenAddr := fmt.Sprintf("%s:%s", ip, "2377")
	Req := swarm.JoinRequest{
		ListenAddr:    listenAddr,
		AdvertiseAddr: fmt.Sprintf("%s:%s", "192.168.34.136", "2377"),
		RemoteAddrs:   remoteAddr,
		JoinToken:     swarmInfo.JoinTokens.Worker,
	}

	err = cli.SwarmJoin(context.TODO(), Req)

	if err != nil {
		fmt.Println(err.Error())
	}

	return
}
